import { isPromise } from "../utils/utils.js"

export const initInterceptors = function() {
	/**
	 * 拦截系统toast
	 */
	uni.addInterceptor("showToast", {
		invoke(args) {
			args.icon = "none"
			args.success = args.success ? args.success:() => {}
			args.fail = args.fail ? args.fail:() => {}
			args.duration = args.duration || 3000
			args.complete = args.complete ? args.complete:() => {}
			 
			if(args.interceptor == undefined || args.interceptor == null) {
				args.interceptor = true
			}
			
			if(!args.interceptor) {
				return true
			}
			
			if(args.title === "interceptor uni.showToast success，so the default implementation of uni.showToast will not excute") {
				return false
			}
			
			let pages = getCurrentPages()
			let currentPage = null
			if(pages && pages.length > 0) {
				currentPage = pages[pages.length - 1]
			}
			
			if(currentPage && currentPage.$vm && currentPage.$vm.$nextTick) {
				return new Promise((resolve, reject) => {
					currentPage.$vm.$nextTick(() => {
						if(currentPage.$customPage) {
							currentPage.$customPage.showMessage({
								message: args.title,
								type: args.type,
								duration: args.duration,
								complete: args.complete
							})
							console.warn("interceptor uni.showToast success，so the default implementation of uni.showToast will not excute")
							// reject("interceptor uni.showToast success，so the default implementation of uni.showToast will not excute")
						} else {
							resolve(args)
						}
					})
				})
			} else {
				return Promise.resolve(args)
			}
		}
	})
	
	uni.addInterceptor("showLoading", {
		invoke(args) {
			args.title = "加载中"
			args.mask = true
			return true
		}
	})
	
	uni.addInterceptor("navigateBack", {
		invoke(args) {
			let url = args.url || ""
			if(url) {
				let pages = getCurrentPages().map((item, index) => "/" + item.route)
				let index = pages.indexOf(url)
				if(index != -1) {
					args.delta = pages.length - (index + 1)
				}
			}
			return true
		}
	})
	
	uni.addInterceptor({
		returnValue(res) {
			if(isPromise(res)) {
				return res.catch((err) => {
					console.warn(err.errMsg)
				})
			} else {
				return res
			}
		}
	})
}